package org.jeecg.modules.flower.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.flower.entity.FlowerCustom;
import org.jeecg.modules.flower.entity.FlowerOutorder;
import org.jeecg.modules.flower.service.IFlowerCustomService;

import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.flower.service.XsglService;
import org.jeecg.modules.flower.util.CommonUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 客户管理
 * @Author: jeecg-boot
 * @Date: 2022-08-29
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "客户管理")
@RestController
@RequestMapping("/flower/flowerCustom")
public class FlowerCustomController extends JeecgController<FlowerCustom, IFlowerCustomService> {
    @Autowired
    private IFlowerCustomService flowerCustomService;

    @Autowired
    private XsglService xsglService;

    /**
     * 分页列表查询
     *
     * @param flowerCustom
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "客户管理-分页列表查询")
    @ApiOperation(value = "客户管理-分页列表查询", notes = "客户管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(FlowerCustom flowerCustom,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
//		QueryWrapper<FlowerCustom> queryWrapper = QueryGenerator.initQueryWrapper(flowerCustom, req.getParameterMap());
        Page<FlowerCustom> page = new Page<FlowerCustom>(pageNo, pageSize);
        LambdaQueryWrapper<FlowerCustom> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(flowerCustom.getName())) {
            lambdaQueryWrapper.like(FlowerCustom::getName, flowerCustom.getName());
        }
        if (StringUtils.isNotBlank(flowerCustom.getCode())) {
            lambdaQueryWrapper.like(FlowerCustom::getCode, flowerCustom.getCode());
        }
        if (StringUtils.isNotBlank(flowerCustom.getPhone())) {
            lambdaQueryWrapper.like(FlowerCustom::getPhone, flowerCustom.getPhone());
        }
        if (StringUtils.isNotBlank(flowerCustom.getAddress())) {
            lambdaQueryWrapper.like(FlowerCustom::getAddress, flowerCustom.getAddress());
        }
        if (StringUtils.isNotBlank(flowerCustom.getSource())) {
            lambdaQueryWrapper.like(FlowerCustom::getSource, flowerCustom.getSource());
        }
        IPage<FlowerCustom> pageList = flowerCustomService.page(page, lambdaQueryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param flowerCustom
     * @return
     */
    @AutoLog(value = "客户管理-添加")
    @ApiOperation(value = "客户管理-添加", notes = "客户管理-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody FlowerCustom flowerCustom) {

        String code = flowerCustom.getCode();
        String phone = flowerCustom.getPhone();
        LambdaQueryWrapper<FlowerCustom> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(FlowerCustom::getCode, code);
        List<FlowerCustom> list = flowerCustomService.list(lambdaQueryWrapper1);
        if (list.size() > 0) {
            throw new RuntimeException(code + "账号重复，请修改后再保存！原账号为：" + list.get(0).getCode());
        }
        LambdaQueryWrapper<FlowerCustom> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(FlowerCustom::getPhone, phone);
        List<FlowerCustom> list2 = flowerCustomService.list(lambdaQueryWrapper2);
        /*if (list2.size() > 0) {
            throw new RuntimeException(phone + "电话号码重复，请修改后再保存！原客户为：" + list2.get(0).getName());
        }*/
        //自动生成编码
        // 规则 ：9为流水   4开头 流水8位
        String refex = "4";
        LambdaQueryWrapper<FlowerCustom> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.likeRight(FlowerCustom::getCode, refex);
        lambdaQueryWrapper.last("limit  0,1");
        lambdaQueryWrapper.orderByDesc(FlowerCustom::getCode);
        List<FlowerCustom> oldList = flowerCustomService.list(lambdaQueryWrapper);
        String oldNo = "";
        if (oldList.size() > 0) {
            oldNo = oldList.get(0).getCode();
        }
        String no1 = CommonUtil.getNoNoDate("4", oldNo, 8);
        flowerCustom.setCode(no1);

        flowerCustomService.save(flowerCustom);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param flowerCustom
     * @return
     */
    @AutoLog(value = "客户管理-编辑")
    @ApiOperation(value = "客户管理-编辑", notes = "客户管理-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<?> edit(@RequestBody FlowerCustom flowerCustom) {
        String code = flowerCustom.getCode();
        String phone = flowerCustom.getPhone();
        LambdaQueryWrapper<FlowerCustom> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(FlowerCustom::getCode, code);
        lambdaQueryWrapper1.ne(FlowerCustom::getId, flowerCustom.getId());
        List<FlowerCustom> list = flowerCustomService.list(lambdaQueryWrapper1);
        if (list.size() > 0) {
            throw new RuntimeException(code + "账号重复，请修改后再保存！原账号为：" + list.get(0).getCode());
        }
        LambdaQueryWrapper<FlowerCustom> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(FlowerCustom::getPhone, phone);
        lambdaQueryWrapper2.ne(FlowerCustom::getId, flowerCustom.getId());
        List<FlowerCustom> list2 = flowerCustomService.list(lambdaQueryWrapper2);
        /*if (list2.size() > 0) {
            throw new RuntimeException(phone + "电话号码重复，请修改后再保存！原客户为：" + list2.get(0).getName());
        }*/

        flowerCustomService.updateById(flowerCustom);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "客户管理-通过id删除")
    @ApiOperation(value = "客户管理-通过id删除", notes = "客户管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        flowerCustomService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "客户管理-批量删除")
    @ApiOperation(value = "客户管理-批量删除", notes = "客户管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.flowerCustomService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "客户管理-通过id查询")
    @ApiOperation(value = "客户管理-通过id查询", notes = "客户管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        FlowerCustom flowerCustom = flowerCustomService.getById(id);
        return Result.OK(flowerCustom);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param flowerCustom
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, FlowerCustom flowerCustom) {
        return super.exportXls(request, flowerCustom, FlowerCustom.class, "客户管理");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, FlowerCustom.class);
    }


    @AutoLog(value = "手动从销售系统汇总同步客户")
    @ApiOperation(value = "手动从销售系统汇总同步客户", notes = "手动从销售系统汇总同步客户")
    @GetMapping(value = "/getCoustomFromSealTolocal")
    public Result<?> getCoustomFromSealTolocal() throws IOException {
        Integer xsglUser = xsglService.getXSGLUser();
        return Result.OK( xsglUser );
    }

    @AutoLog(value = "获取客户余额")
    @ApiOperation(value = "获取客户余额", notes = "获取客户余额")
    @GetMapping(value = "/getCustomMoney")
    public Result<?> getCoustomMoney(@RequestParam("userId")String userId) throws IOException {
        BigDecimal userMoney = xsglService.getXSGLUserMoney(userId);
        return Result.ok(userMoney);
    }
}
